﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BlackBird.Models;

namespace BlackBird.DataAccess
{
    public static class ProductDataAccess
    {
        static List<ProductDM> all_products = new List<ProductDM>();

        public static List<ProductDM> ProductList
        {
            get { return AllProductsDM(); }
        }

        public static List<ProductDM> AllProductsDM()
        {
            if (all_products.Count > 0) return all_products;

            using (var dbContext = new blackbirdEntities())
            {
                dbContext.product.ToList().ForEach(p => all_products.Add(BuildProductDM(p)));
            }

            return all_products;
        }

        public static void AddProduct(ProductDM dm)
        {
            var findProduct = all_products.Find(p => p.Name.Equals(dm.Name));
            if (findProduct != null) return;

            all_products.Add(dm);
        }

        public static product SaveToDatabase(ProductDM productDm)
        {
            using (var dbContext = new blackbirdEntities())
            {
                int productDmId = Convert.ToInt32(productDm.Id);
                //这里也判断同名的情况，避免同一个产品被添加多次
                var productDb = dbContext.product.FirstOrDefault(p => 
                    p.idProduct == productDmId);

                //update exist entity
                if (productDb != null)
                {
                    productDb.Name = productDm.Name;
                    productDb.Unit = productDm.Unit;
                    productDb.GuiGe = productDm.GuiGe;

                    productDm.Id = productDb.idProduct.ToString();
                    dbContext.SaveChanges();
                }
                else //add new entity
                {
                    productDb = product.Createproduct(0);
                    productDb.Name = productDm.Name;
                    productDb.Unit = productDm.Unit;
                    productDb.GuiGe = productDm.GuiGe;

                    dbContext.product.AddObject(productDb);
                    dbContext.SaveChanges();

                    //update the id for DM after db save changes
                    productDm.Id = productDb.idProduct.ToString();
                }

                return productDb;
            }
        }

        public static ProductDM BuildProductDM(product dbObject)
        {
            return new ProductDM()
            {
                Id = dbObject.idProduct.ToString(),
                Name = dbObject.Name,
                Unit = dbObject.Unit,
                GuiGe = dbObject.GuiGe
            };
        }
    }
}